﻿using IOA.MES.Client.Common;
using IOA.MES.Client.Models.Response;
using IOA.MES.Client.Settings;
using IOA.MES.Common;
using Newtonsoft.Json;
using NLog;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;


namespace IOA.MES.Client.IV
{
    /// <summary>
    /// WinPassIv.xaml 的交互逻辑
    /// </summary>
    public partial class WinPassIv : Window
    {
        private List<KeyValuePair<string, string>> ivDatas = new List<KeyValuePair<string, string>>();
        private string lastBarCode = string.Empty;
        private string lastImage = string.Empty;
        private string curDirectory;
        public WinPassIv()
        {
            InitializeComponent();
        }

        
        private DataTable GetLastData(string fileName, string barCode)
        {
            var machines = BaseEnv.InvokeApi<QueryMachinesResponse>("/api/Machine/QueryMachines", new { WorkshopCode = BaseEnv.WorkshopCode, MachineType = (int)MachineType.IV }).Data.Machines;

            var machine = machines.FirstOrDefault(_ => _.MachineId == BaseEnv.MachineId);
            string machinsql = machine.IvSql.ToString();
            string[] machinesqls = machinsql.Split('=');
            var Code = machinesqls[0].Substring(machinesqls[0].IndexOf(",") + 1, machine.IvSql.ToUpper().IndexOf("AS BARCODE")- machinesqls[0].IndexOf(",")-1);
            try
            {
                string sql = machinesqls[0].Substring(0,machinesqls[0].LastIndexOf("1"))+" " + Code + "= '" + barCode + "' " + machinesqls[1].Substring(machinesqls[1].IndexOf("1"));
                
                
                
                var conn = new OleDbConnection($"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={fileName}");
                conn.Open();
                var cmd = conn.CreateCommand();
                cmd.CommandText = sql;
                var dr = cmd.ExecuteReader();
                DataTable dt = new DataTable();
                if (dr.HasRows)
                {
                    for (int i = 0; i < dr.FieldCount; i++)
                    {
                        dt.Columns.Add(dr.GetName(i));
                    }
                    dt.Rows.Clear();
                }
                while (dr.Read())
                {
                    DataRow row = dt.NewRow();
                    for (int i = 0; i < dr.FieldCount; i++)
                    {
                        row[i] = dr[i];
                    }
                    dt.Rows.Add(row);
                }
                cmd.Dispose();
                conn.Close();

                return dt;
            }
            catch (Exception ex)
            {
                CommonMessage.Alert(this, $"读取Access出错\r\nError reading Access：\r\n{ex.ToString()}", false);
                return null;
            }
        }

        /// <summary>
        /// 处理过站数据
        /// </summary>
        private void OperateData(DataTable dt)
        {
            ivDatas.Clear();
            if (dt == null || dt.Rows.Count <= 0)
            {
                CommonMessage.Log(LogLevel.Warn, $"未找到条码数据\r\nError reading Access");
                return;
            }
            else if (string.IsNullOrWhiteSpace(dt.Rows[0]["BarCode"].ToString()))
            {
                CommonMessage.Log(LogLevel.Warn, "组件条码为空\r\nComponent barcode is empty");
                return;
            }

            lastBarCode = dt.Rows[0]["BarCode"].ToString().Trim();
            foreach (DataColumn column in dt.Columns)
            {
                ivDatas.Add(new KeyValuePair<string, string>(column.ColumnName, dt.Rows[0][column].ToString()));
            }

            TryViaSite();
        }

        private void TryViaSite()
        {
            try
            {
                var viaSiteRequest = new
                {
                    SiteType = SiteType.IVTest,
                    DutyId = 1,
                    MachineId = BaseEnv.MachineId,
                    Code = ivDatas.FirstOrDefault(_ => string.Equals(_.Key, "BarCode")).Value,
                    IVData = ivDatas,
                    Images = new List<string>()
                };

                try
                {
                    lastImage = $@"{txtImageFolder.Text}\{lastBarCode}.jpg";
                    if (File.Exists(lastImage))
                    {
                        var getComponentResponse = BaseEnv.InvokeApi<GetComponentResponse>("/api/Machine/GetComponent", new { BarCode = viaSiteRequest.Code });
                        Dispatcher.Invoke(new Action(() =>
                        {
                            if (getComponentResponse.ErrCode != 200)
                            {
                                mediaElResult.Source = new Uri($"{BaseEnv.LocalDirectory}\\res\\audio\\Fail.wav");
                                mediaElResult.Play();
                                CommonMessage.Log(LogLevel.Warn, getComponentResponse.ErrMsg);
                                return;
                            }
                            else if (getComponentResponse.Data == null || getComponentResponse.Data.Component == null)
                            {
                                mediaElResult.Source = new Uri($"{BaseEnv.LocalDirectory}\\res\\audio\\Fail.wav");
                                mediaElResult.Play();
                                CommonMessage.Log(LogLevel.Warn, $"组件不存在\r\nComponent does not exist：\r\n{viaSiteRequest.Code}");
                                return;
                            }
                        }));
                        var tmpDirectory = $"/{BaseEnv.WorkshopCode}/IV/{getComponentResponse.Data.Component.WorkOrderNo}";
                        if (string.IsNullOrWhiteSpace(curDirectory) || !string.Equals(curDirectory, tmpDirectory, StringComparison.CurrentCultureIgnoreCase))
                        {
                            new FtpUtils(BaseEnv.UserInfo.FtpConfig.FtpRoot, BaseEnv.UserInfo.FtpConfig.UserName, BaseEnv.UserInfo.FtpConfig.Password).CheckAndCreateDirectory(tmpDirectory);
                            curDirectory = tmpDirectory;
                        }
                        var fileName = $"{curDirectory}/{viaSiteRequest.Code}_{DateTime.Now:yyMMddHHmmss}.jpg";
                        var fileBytes = File.ReadAllBytes(lastImage);
                        new FtpUtils(BaseEnv.UserInfo.FtpConfig.FtpRoot, BaseEnv.UserInfo.FtpConfig.UserName, BaseEnv.UserInfo.FtpConfig.Password).Upload(fileBytes, fileName);
                        viaSiteRequest.Images.Add($"{BaseEnv.UserInfo.FtpConfig.FtpRoot}/{fileName}");
                    }
                }
                catch (Exception ex)
                {
                    CommonMessage.Log(LogLevel.Warn, $"图片上传失败：{ex.Message}");
                    return;
                }

                var response = BaseEnv.InvokeApi<ViaSiteResponse>("/api/Machine/ViaSite", viaSiteRequest);
                Dispatcher.Invoke(new Action(() =>
                {
                    if (response.ErrCode != 200)
                    {
                        mediaElResult.Source = new Uri($"{BaseEnv.LocalDirectory}\\res\\audio\\Fail.wav");
                        mediaElResult.Play();
                        CommonMessage.Log(LogLevel.Warn, response.ErrMsg);
                        return;
                    }
                    else if (response.Data.StandardTestResult != null)
                    {
                        if (response.Data.StandardTestResult.Pass)
                        {
                            CommonMessage.Log(LogLevel.Warn, $"标片测试通过：{lastBarCode}");
                        }
                        else
                        {
                            CommonMessage.Log(LogLevel.Warn, $"标片测试不通过：{lastBarCode}，异常信息：{response.Data.StandardTestResult.ErrMsg}");
                            CommonMessage.Log(LogLevel.Warn, $"标片检测不合格，标片标准值和当前测试值分别为\r\nThe standard test fails, the standard value of the standard and the current test value are\r\n：{response.Data.StandardTestResult.ErrMsg}");
                        }
                        return;
                    }
                    CommonMessage.Log(LogLevel.Info, $"过站成功：{lastBarCode}");
                    mediaElResult.Source = new Uri($"{BaseEnv.LocalDirectory}\\res\\audio\\Success.wav");
                    mediaElResult.Play();
                }));
            }
            catch (Exception ex)
            {
                CommonMessage.Log(LogLevel.Warn, $"过站失败，请拍照发给IT，并重新尝试过站\r\nPassing failed, please take a picture and send it to IT\r\n{ex.ToString()}");
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var barCodes = txtBarCode.Text.Trim().Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList();
            if (!barCodes.Any())
            {
                System.Windows.MessageBox.Show("条码为空");
                return;
            }

            foreach (var barCode in barCodes)
            {
                try
                {
                    var dt = GetLastData(txtDataSource.Text.Trim(), barCode);
                    OperateData(dt);
                }
                catch (Exception ex)
                {
                    System.Windows.MessageBox.Show($"条码过站异常，条码：{barCode}，异常信息：{ex.ToString()}");
                }
            }
            System.Windows.MessageBox.Show("处理完成！");
        }
    }
}
